#!/bin/bash
set -euxo pipefail

if [ "$#" -lt 1 ] || [ "$#" -gt 3 ]; then
  echo "Usage: $0 <deployment> [description] [rollout_percentage]"
  echo "Deployment must be either 'canary', 'staging' or 'production'."
  echo "Rollout percentage is optional (integer from 0 to 100)."
  exit 1
fi

deployment=$1

if [ "$deployment" != "canary" ] && [ "$deployment" != "staging" ] && [ "$deployment" != "production" ]; then
  echo "Invalid deployment option: $deployment"
  echo "Deployment must be either 'canary', 'staging' or 'production'."
  exit 1
fi

# Get the description from the command-line argument if provided, otherwise use the last commit hash and description
description=""
if [ -n "${2:-}" ]; then
  description="$2"
else
  commit_hash=$(git rev-parse --short HEAD)
  commit_description=$(git log -1 --pretty=%s)
  description="Commit: $commit_hash, Description: $commit_description"
fi

rollout=""
if [ -n "${3:-}" ]; then
  rollout="rollout_percentage:$3"
fi

if [ -n "$rollout" ]; then
  bundle exec fastlane deploy_to_expo_updates deployment_name:$deployment description:"$description" platform:ios "$rollout"
  bundle exec fastlane deploy_to_expo_updates deployment_name:$deployment description:"$description" platform:android "$rollout"
else
  bundle exec fastlane deploy_to_expo_updates deployment_name:$deployment description:"$description" platform:ios
  bundle exec fastlane deploy_to_expo_updates deployment_name:$deployment description:"$description" platform:android
  # reset changes made to app.json
  git checkout app.json
  git checkout dist/.gitkeep
fi

echo "Release to $deployment deployment successful."